import store, { setStore } from "../store";
import { apiPre, baseURL } from "./config";
import { supabase } from "./supabase";

const { http } = uni.$u;
uni.$api = http;

http.setConfig((config) => {
  config.baseURL = baseURL;
  config.timeout = 30e3;
  return config;
});

async function getToken() {
  if (uni.$h.inMp) {
    const { data } = await supabase.auth.getSession();
    return data?.session?.access_token;
  }
  return store.state.usrData.token;
}

http.interceptors.request.use(
  async (config) => {
    const { header, params } = config;
    const token = await getToken();
    if (token) {
      header.Authorization = `Bearer ${token}`;
    }
    if (/^\$/.test(config.url)) {
      for (const key in apiPre) {
        const reg = new RegExp("^\\$" + key);
        config.url = config.url.replace(reg, apiPre[key]);
      }
    }
    return config;
  },
  (config) => {
    return Promise.reject(config);
  }
);

function handErr(e) {
  console.log(e);
  let { data = {}, config } = e;
  let msg = `${e.statusCode} error`;
  if (data && typeof data == "object") {
    msg = data.errMsg || data.msg || data.message;
  }
  if (e.statusCode == 401) {
    const pages = getCurrentPages();
    const len = pages.length;
    const curPage = pages[len - 1];
    const act = len == 1 ? "navigateTo" : "redirectTo";
    store.dispatch("logout");
    uni.hideLoading();
    uni.$navTo("mine/login", act, {
      to: curPage.route,
    });
  } else if (!config.custom.noTip) {
    if (/fail abort/.test(msg) || msg == "request:fail") {
      msg = "网络异常"; //
    }
    if (msg) {
      e.msg = msg;
      setTimeout(() => {
        uni.showToast({
          title: msg,
          icon: "none",
          duration: 2000,
        });
      }, 10);
    }
  }
  return Promise.reject(e);
}

http.interceptors.response.use(
  (res) => {
    const { data } = res;
    if (typeof data == "object" && "code" in data) {
      if (data.code !== 0) {
        return handErr(res);
      }
      // return data;
    }
    return res;
  },
  (res) => {
    console.log("err", res);
    return handErr(res);
  }
);
